package cn.ycbjie.ycaudioplayer.ui.study.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.synjones.minnovate.frame.basesdk.http.SynHttp;
import com.synjones.minnovate.frame.basesdk.http.SynSchedulersTranfs;
import com.synjones.minnovate.frame.basesdk.http.exception.AbsRxSubscriber;
import com.synjones.minnovate.frame.basesdk.http.exception.ApiException;
import com.synjones.minnovate.frame.basesdk.log.SynLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.base.BaseFragment;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.animtion.RefreshItemDecoration;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.iapiserver.iapi;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.mybeans.MyFinderlistBean;
import cn.ycbjie.ycaudioplayer.ui.study.ui.adapter.MyFinderAdapter;

import static cn.ycbjie.ycaudioplayer.newpack.linkagescroll.config.MyConfig.baseURL;


public class FinderFragmentbeifen extends BaseFragment {
    private RecyclerView v7_widget_finder_list_view;
    private SwipeRefreshLayout v4_swi_finder_laout;
    MyFinderAdapter adapterlist;
    Context mcontext;
    int zongpage = 1;
    List<MyFinderlistBean> mDatas = new ArrayList<>();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mcontext = context;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =LayoutInflater.from(getActivity()).inflate(R.layout.finderfragment, container, false);
        initView(view);
        //初始化view
        //加载数据
        initData();
        //下拉和上拉的监听
        initListener();
        ListView lis;

        return view;


    }

    @Override
    public int getContentView() {
        return R.layout.base_easy_recycle;
    }

    @Override
    public void initView() {

    }

    private void initView(View view) {
//       WebView web_test = (WebView)view.findViewById(R.id.web_test);
//        WebSettings settings = web_test.getSettings();
//        settings.setJavaScriptEnabled(true);
//        settings.setDomStorageEnabled(true);
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        web_test.setWebViewClient(new MyWebViewClient());
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
//        } else {
//            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
//        }
//        if (web_test.isHardwareAccelerated()) settings.setJavaScriptEnabled(true);
//       web_test.loadUrl("http://www.baidu.com");
        v4_swi_finder_laout = (SwipeRefreshLayout)view.findViewById(R.id.v4_swi_finder_laout);
        v7_widget_finder_list_view = (RecyclerView)view.findViewById(R.id.v7_widget_finder_list_view);

        //设置加载时的大小
        v4_swi_finder_laout.setSize(SwipeRefreshLayout.DEFAULT);


        //设置加载条的颜色切换
        v4_swi_finder_laout.setColorSchemeColors(ContextCompat.getColor(mcontext,R.color.a),
                ContextCompat.getColor(mcontext,R.color.b),
                ContextCompat.getColor(mcontext,R.color.c));
        //设置加载时的背景色
        v4_swi_finder_laout.setProgressBackgroundColorSchemeColor(ContextCompat.getColor(mcontext,R.color.srlbg));
        //下拉多少距离开始刷新
        v4_swi_finder_laout.setDistanceToTriggerSync(100);
    }

    /**
     * 设置数据
     */
    public void initData() {

   getfinderlist("1","1","",true);
        //设置布局管理器

    }


    /**
     * 设置布局管理器
     */
    private void initRecylerView(List<MyFinderlistBean> dt) {
        adapterlist = new MyFinderAdapter(mcontext, dt);
        //添加动画
        v7_widget_finder_list_view.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        v7_widget_finder_list_view.addItemDecoration(new RefreshItemDecoration(mcontext,RefreshItemDecoration.VERTICAL_LIST));

        //第三个参数是  排列顺序  true 数据倒序,false数据正序
        v7_widget_finder_list_view.setLayoutManager(new LinearLayoutManager(mcontext, LinearLayoutManager.VERTICAL, false));

        v7_widget_finder_list_view.setAdapter(adapterlist);
    }

    public void initListener() {
//        initPullListener();
        initLoadMoreListen();
    }

//    private void initPullListener() {

//        //swiperefreshLayout  下拉刷新的监听
//        v7_widget_finder_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//
//                //模拟子线程中加载数据
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //设置假数据
//                        List<String> headDatas=new ArrayList<String>();
//                        for (int i=20;i<30;i++){
//                            headDatas.add("HeadItem "+i);
//                        }
//                        //下拉时添加在列表的头部
//                        adapterlist.addHeadItem(headDatas);
//                        //停止刷新
//                        first_srl.setRefreshing(false);
//                        Toast.makeText(mcontext, "下拉加载数据", Toast.LENGTH_SHORT).show();
//                    }
//                },3000);//注意,是在30000ms中完成
//
//            }
//        });
//    }

    /**
     * 上拉加载
     */
    private void initLoadMoreListen() {
        //RecycleView的滚动监听  滚动到最后一个条目时进行设置
        v7_widget_finder_list_view.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int lastVisibleItem;//列表最后显示出来的条目

            @Override//滚动状态改变时
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //只要最后一个条目滑动出来就
                //设置正在加载的状态
                adapterlist.changeMoreState(adapterlist.LOADING_MORE);


                //newState判断RecyclerView的状态 是空闲时，
                // 同时，是最后一个可见的ITEM时才加载
                if (newState== RecyclerView.SCROLL_STATE_IDLE&&
                        lastVisibleItem+1==adapterlist.getItemCount()){

                    getfinderlist("1",(zongpage++)+"","",false);
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            List<String> footerDatas=new ArrayList<String>();
//                            for (int i=0;i<10;i++){
//                                footerDatas.add("foot item "+i);
//                            }
//                            //添加数据到列表的底部
//                            adapterlist.addFootItem(footerDatas);
//
//                            //设置回到上拉加载状态
//                            adapterlist.changeMoreState(adapterlist.PULLUP_LOAD_MORE);
//
//                            //没有加载更多了
//                            //mRefreshAdapter.changeMoreStatus(mRefreshAdapter.NO_LOAD_MORE);
//                            Toast.makeText(mcontext, "上拉更新了"+footerDatas.size()+"条数据", Toast.LENGTH_SHORT).show();
//
//                        }
//                    },3000);
                }
            }

            @Override//滚动时
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutmanager= (LinearLayoutManager) v7_widget_finder_list_view.getLayoutManager();
                lastVisibleItem=layoutmanager.findLastVisibleItemPosition();
            }
        });
    }



    private void getfinderlist(String type, final String page, String orderBy, final Boolean isfirst) {

        SynHttp.getInstance().getApi(baseURL, iapi.class).getfinderlist(type, page, orderBy)
                .compose(SynSchedulersTranfs.<String>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<String>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }

                    final ArrayList<MyFinderlistBean> lcs = new ArrayList<MyFinderlistBean>();

                    public void onNext(String weatherInfoBean) {

                        try {
                            JSONObject obj = new JSONObject(weatherInfoBean.toString());
                            String code = obj.getString("code");
                            String data = obj.getString("data");

                            JSONObject objer = new JSONObject(data);
                            JSONArray jsonArray = objer.getJSONArray("data");
                            String dataer = objer.getString("data");
                            int total = Integer.parseInt(objer.getString("total"));
                            int limit = 100;//Integer.parseInt(objer.getString("limit"));
                            int pp  = total/limit+1;
                            Gson gson = new Gson();
                            JsonParser parser = new JsonParser();
                            JsonArray Jarray = parser.parse(dataer).getAsJsonArray();
                            for (JsonElement objel : Jarray) {
                                MyFinderlistBean cse = gson.fromJson(objel, MyFinderlistBean.class);
                                lcs.add(cse);

                            }
                            if(isfirst)
                            {
                                initRecylerView(lcs);
                            }
                            else
                            {
                                //添加数据到列表的底部

                                if(pp<Integer.parseInt(page))
                                {
                                    //没有加载更多了
                                    adapterlist.changeMoreState(adapterlist.NO_LOAD_MORE);
                                }

                                else
                                    {
                                    adapterlist.addFootItem(lcs);

                                    //设置回到上拉加载状态
                                    adapterlist.changeMoreState(adapterlist.PULLUP_LOAD_MORE);


                                    Toast.makeText(mcontext, "上拉更新了" + lcs.size() + "条数据", Toast.LENGTH_SHORT).show();
                                }
                            }
//                            if (adapterlist==null) {
//                                dropListView = (DropListView) findViewById(R.id.list_view_id);
//                                lv.setInterface(test_musicplayer.this);//设置回调接口
//                            adapterlist = new MyFinderAdapter(mcontext, lcs);
//                                lv.setAdapter(adapterlist);
//                            }else {
//                                adapterlist.onDateChange();
//                            }

//                            adapterlist = new MyAdapter(test_musicplayer.this, lcs);
//                            lv.setInterface(test_musicplayer.this);//设置回调接口

//                            ref_finderlist.setAdapter(adapterlist);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        SynLog.file("String----->" + weatherInfoBean.toString());
                    }
                });

    }
}
